#_*_coding:utf-8_*_
from __future__ import division
import boto
from boto.s3.key import Key
import os,time
from os.path import join, getsize

def getdirsize(dir):
	size = 0L
	for root, dirs, files in os.walk(dir):
		size += sum([getsize(join(root, name)) for name in files])
	return size/1024/1024



def listgroupby(li,m):
	n80 = 0
	n90 = 0
	n95 = 0
	total = len(li)
	for i in li:
		if i <= m*0.8:
			n80+=1
		if i <= m*0.9:
			n90+=1
		if i <= m*0.95:
			n95+=1
	return '''Lessthan  %f : %d%% , Lessthan %f : %d%% ,Lessthan %f : %d%%  '''%(m*0.8,n80/total*100,m*0.9,n90/total*100,m*0.95,n95/total*100)
def lgroupby(li):
	m = len(li)
	li.sort()
	m80 = li[int(m*0.8)]
	m90 = li[int(m*0.9)]
	m95 = li[int(m*0.95)]
	m99 = li[int(m*0.99)]
	return '''80%% : %f  , 90%% : %f ,95%% : %f ,99%% : %f'''%(m80,m90,m95,m99)
	
	


def ListBuckets(conn):
    for bucket in conn.get_all_buckets():
        print "{name}\t{created}".format(
                name = bucket.name,
                created = bucket.creation_date,
    )
def CreateBucket(conn,bucketname):
    try:
	conn.create_bucket(bucketname)
	print "Create %s Success"%bucketname
    except  Exception as e:
	print e


def UploadFile(conn,bucketname,source_path):
    try:
	start = time.time()
    	bucket = conn.get_bucket(bucketname)
	key = Key(bucket, source_path)
	key.set_contents_from_filename(source_path, policy='public-read')
	end = time.time()
    	return os.getpid(),end-start,0 #pid  dealtime success
    except  Exception as e:
	end = time.time()
	return os.getpid(),end-start,1  #pid dealtime mission  
	pass

def DownloadFile(conn,bucketname,source_path):
    try:
	start = time.time()
    	bucket = conn.get_bucket(bucketname)
	key = Key(bucket, source_path)
	local_file='./downloads/'+source_path
	key.get_contents_to_filename(local_file)
	end = time.time()
    	return os.getpid(),end-start,0 #pid  dealtime success
    except  Exception as e:
	end = time.time()
	return os.getpid(),end-start,1  #pid dealtime mission  

